var jwxa = {},
    // 请求默认设置
    __requestSettings = {
        header: {
            'content-type': 'application/json'
        },
        method: 'GET',
        dataType: 'json',
        success: _empty,
        fail: _empty,
        complete: _empty
    };
// 空函数
function _empty() {}
// url追加参数
function _appendQuery(url, query) {
    if (query == '') return url;
    return (url + '&' + query).replace(/[&?]{1,2}/, '?');
}
// 解析参数
function _parseArguments(url, data, success, fail) {
    if(jwxa.isFunction(data)) {
        fail = success, success = data, data = undefined;
    }
    return {
        url: url,
        data: data,
        success: success,
        fail: fail
    };
}
// 发起wx请求
function _request(options) {
    var settings = options || {};
    for (var key in __requestSettings) {
        if (settings[key] === undefined) settings[key] = __requestSettings[key];
    };
    wx.request(settings);
}

// 是否是函数
jwxa.isFunction = function(value) {
    return (typeof value) == "function";
}
// 是否是对象
jwxa.isObject = function(obj) {
    return (typeof obj) == "object";
}
// this
jwxa.init = function(target) {
    this.__target = target;
    return this;
}
// get 请求
jwxa.get = function() {
    return _request(_parseArguments.apply(null, arguments));
};
/*
 设置data{}, 支持点操作符
 说明:
 jwxa.data({key: value}); 相当于this.setData();
 jwxa.data('key1.key2.key3', 'ok'); 相当于设置了{key1: {key2: {key3: 'ok'}}}
 */
jwxa.data = function(name, value) {
    if(this.isObject(name)) {
        this.__target.setData(name);
    } else {
        var keyArray = name.split(".");
        if(!keyArray && keyArray.length < 1) {
            return ;
        }
            // 根节点Key
        var rootKey = keyArray[0],
            // 下一个节点Key
            nextKey,
            // 根节点对象
            rootObj = keyArray.length == 1 ? value : (this.__target.data[rootKey] || {}),
            // 上一个节点对象
            prevObj = rootObj;
        for(var i=1; i<keyArray.length; ++i) {
            nextKey = keyArray[i];
            prevObj = prevObj[nextKey] = i == keyArray.length - 1 ? value : prevObj[nextKey] || {};
        }
        var dataValue = {};
        dataValue[rootKey] = rootObj;
        this.__target.setData(dataValue);
    }
}
// 字符串解析成JSON对象
jwxa.parseJSON = JSON.parse;

module.exports = jwxa;